package routes

import (
	"embed"
	"manage/internal/routes/common"
	"manage/internal/routes/middleware"
	"net/http"

	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
)

//go:embed pages/404.html
var NoPage []byte

//go:embed pages/index.html
var IndexPage []byte

//go:embed pages/500.html
var ErrorPage []byte

//go:embed assets/**
var BuildFS embed.FS

func HomePage(c *gin.Context) {
	c.Data(
		http.StatusOK,
		"text/html; charset=utf-8",
		IndexPage,
	)
}

func NotFoundPage(page int) func(c *gin.Context) {
	var content []byte

	switch page {
	case 404:
		content = NoPage
	case 500:
		fallthrough
	default:
		content = ErrorPage
	}

	return func(c *gin.Context) {
		c.Data(
			http.StatusOK,
			"text/html; charset=utf-8",
			content,
		)
	}
}

func InitConfig(engine *gin.Engine) {
	// 主页面
	engine.GET("/", HomePage)
	// 中间件
	engine.Use(
		Cors(),
		middleware.ErrorHttp,
		static.Serve("/", common.EmbedFolder(BuildFS, "assets")),
	)
	// 日志和错误恢复
	engine.Use(
		gin.Recovery(), // 错误恢复
		gin.LoggerWithConfig( // 替换默认日志
			gin.LoggerConfig{Formatter: middleware.LoggerWithFormatter},
		),
	)
	// 页面未找到
	engine.NoRoute(NotFoundPage(404))
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
